<?php
namespace App\Think\SdkGame;

date_default_timezone_set('PRC');

class YBQP{


    // 登录/注册,上分,下分,查询订单状态,查询玩家额度,修改密码接口地址: 
    // https://uatopenapi.fun100.site 
    // 拉取游戏注单接口地址   
    // https://uatbetinfo.fun100.site 
    // 商户编号:  bt20050702
    // 商户密钥：H5QkHELPa6YdpOnf
    // IV向量：0102030405060708 
    // 具体接入方法详见API文档 。

    // 你好，我方UAT商户管理后台资料如下：
    // 地址 https://uatbackadmin.fun100.site 
    // 账号密码：bt-admin/a12345678

    public function __construct()
    {
        // 商户唯一编码  
        $this->agentid = 'bt20050702';
        // api地址
        $this->api_url  = 'https://uatopenapi.fun100.site/';
        $this->pull_url = 'https://uatbetinfo.fun100.site/';
        $this->secret_key = 'H5QkHELPa6YdpOnf';

        $this->plat_type  = 'YBQP';

        $this->password_init = md5('baote123A');
    }

    /**
     * 注册
     */
    public function register($param){
        $device = @$param['device'] == 'pc' ? 0 : 1;
        $req_data = array(
            'memberId'    => $param['account'],
            'memberName'  => $param['account'],
            'memberPwd'   => $this->password_init,
            'deviceType'  => $device,
            "memberIp"    => request()->ip(),
        );
        $url = $this->build_url('launchGame');
        $res = $this->sendRequest($url, $req_data);
        return $res;
    }
    /**
     * 获取登录链接
     */
    public function login($param){
        $res = $this->register($param);
        return ['code'=>$res['code'], 'url'=>$res['data'] ];
    }
    /**
     * 获取余额
     */
    public function balance($param){
        $req_data = array(
            'memberId'    => $param['account'],
            'memberPwd'   => $this->password_init,
            "memberIp"    => request()->ip(),
        );
        $url = $this->build_url('queryBalance');
        $res = $this->sendRequest($url, $req_data);
        return ['code'=>$res['code'], 'balance'=>(float)$res['data']['balance']/100 ];
    }

    /**
     * 转入资金(上分)
     */
    public function transIn($param){
        $device = @$param['device'] == 'pc' ? 0 : 1;
        $req_data = array(
            'memberId'    => $param['account'],
            'money'   => $param['money']*100,
            'orderId' => $param['account'].':'.$param['orderid'],

            'memberName'  => $param['account'],
            'memberPwd'   => $this->password_init,
            'deviceType'  => $device,
            "memberIp"    => request()->ip(),
        );

        $url = $this->build_url('transferIn', 'api', mb_substr($param['orderid'],0,10) );
        $res = $this->sendRequest($url, $req_data);
        return $res;
    }
    /**
     * 转出资金(下分)
     */
    public function transOut($param){
        $device = @$param['device'] == 'pc' ? 0 : 1;
        $req_data = array(
            'memberId'   => $param['account'],
            'orderId'    => $param['account'].':'.$param['orderid'],
            'money'      => $param['money']*100,

            'memberName'  => $param['account'],
            'memberPwd'   => $this->password_init,
            'deviceType'  => $device,
            "memberIp"    => request()->ip(),
        );
        
        $url = $this->build_url('transferOut', 'api', mb_substr($param['orderid'],0,10) );
        $res = $this->sendRequest($url, $req_data);
        return $res;
    }
    /**
     * 可转出资金查询(下分额度)
     */
    // public function transOutInfo($param){
    //     $req_data = array(
    //         "account" => $param['account']
    //     );
    //     $url = $this->build_url('transferOut');
    //     $res = $this->sendRequest($url, $req_data);
    //     return $res;
    // }


    /**
     * 游戏注单拉取
     */
    public function gameLogSync($param){
        $req_data = array(
            "beginTime" => strtotime($param['startTime']),
            "endTime"   => strtotime($param['endTime']),
            'pageNum'   => 1,
            'pageSize'  => 10000
        );
        $url = $this->build_url('queryGameOrders', 'pull');
        $res = $this->sendRequest($url, $req_data);
        //数据返回处理
        $list = @$res['data']['list'];
        // print_r($list);
        $rs = $raw_data = [];
        $status = 1;
        if(is_array($list) && count($list) > 0){
            foreach ($list as $k => $v) {
                //金额初始化
                $v['mw'] = $v['mw']/100;
                $v['tb'] = $v['tb']/100;
                $v['mp'] = $v['mp']/100;
                $v['bc'] = $v['bc']/100;
                //流水
                if($v['mw'] < 0)  $money_valid = -$v['mw']<$v['tb'] ? -$v['mw'] : $v['tb'];
                if($v['mw'] >= 0) $money_valid = $v['mw']<$v['tb'] ? $v['mw'] : $v['tb'];
                //游戏记录处理
                $rs[$k] = [
                    'plat_type'     => $this->plat_type,
                    'game_type'     => $v['gi'],
                    'game_name'     => $v['gn'],
                    'game_user'     => $v['mmi'],
                    'bet_id'        => $v['bi'],
                    'money_bet'     => $v['tb'],
                    'money_valid'   => $money_valid,
                    'money_winlose' => $v['mw'],
                    'money_fee'     => $v['mp'],
                    'createtime'    => $v['st'],
                    'updatetime'    => $v['et'],
                    'status'        => 1,
                ];
                //源数据处理
                $raw_data[$k] = $v;
                $raw_data[$k]['plat_type'] = $this->plat_type;
                $raw_data[$k]['bet_id']    = $v['bi'];
                $raw_data[$k]['status']    = $status;
                $raw_data[$k]['updatetime'] = strtotime($v['et']);
            }
        }
        $res['list'] = $rs;
        $res['raw_data']  = $raw_data;
        $res['code'] = $res['code'] == -101 ? 1 : $res['code'];
        return $res;
    }



    /**
     * 业务
     */
    //游戏列表
    // private function game_list(){
    //     $list = [

    //     ];
    //     return $list;
    // }
    // private function game_name($gameid){
    //     $list = $this->game_list();
    //     return isset($list[$gameid]) ? $list[$gameid] : '未知游戏';
    // }

    // //房间列表
    // private function room_list(){
    //     $list = [

    //     ];
    //     return $list;
    // }
    // private function room_name($roomid){
    //     $list = $this->room_list();
    //     return isset($list[$roomid]) ? $list[$roomid] : '未知房间';
    // }

    /**
     * --------------
     * 内部方法
     * --------------
     */
    private function sendRequest($url, $post_data=array(), $req_type=1){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //POST
        if($req_type == 1){ 
            curl_setopt($ch, CURLOPT_POST, 1);
            
            $aes = new YBQPAes();  
            $postStr = $aes->encrypt( json_encode($post_data) );  
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: text/plain; charset=utf-8',
                    'Content-Length: ' . strlen($postStr)
                )
            );
            // $postStr = YBQPAes::encrypt( json_encode($post_data) );

            curl_setopt($ch, CURLOPT_POSTFIELDS, $postStr);
        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $contents = curl_exec($ch);
        curl_close($ch);
        // print_r($contents);die;
        $contents = json_decode($contents, true);

        //业务处理
        $res = $contents;
        if(!isset($res['code'])){
          $res['code'] = -1;
          return $res;  
        } 
        if($res['code'] == 1000){
            $res['code'] = 1;  
        }else{
            $res['code'] = -$res['code'];
        }
        return $res;
    }

    
    private function build_url($type='launchGame', $api_type='api', $timestamp=''){
        $timestamp = empty($timestamp) ? time() : $timestamp;
        $randno = $this->rand_str();
        $sign = md5($this->agentid.$timestamp.$this->secret_key);
        $sign = substr_replace($sign, rand_str(2, 'char'), 32, 0);
        $sign = substr_replace($sign, rand_str(2, 'char'), 17, 0);
        $sign = substr_replace($sign, rand_str(2, 'char'), 9, 0);
        $sign = substr_replace($sign, rand_str(2, 'char'), 0, 0);

        $api_url = ($api_type=='pull') ? $this->pull_url : $this->api_url;
        return $api_url.$type.'?agent='.$this->agentid."&timestamp={$timestamp}&randno={$randno}&sign={$sign}";
    }
    private function rand_str($length=10, $type='num')   
    {   
        $key = '';
        $pattern = '0123456789';
        if($type == 'char') $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        if($type == 'lowerchar') $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';  
        for($i=0;$i<$length;$i++) $key .= $pattern{mt_rand(0, iconv_strlen($pattern,"UTF-8")-1)};    //生成php随机数  
        return $key;   
    }

}



class YBQPAes {
    private $iv = "0102030405060708";//密钥偏移量IV，可自定义
    private $encryptKey = "H5QkHELPa6YdpOnf";//AESkey，可自定义

    //加密
    public function encrypt($encryptStr) {
        $localIV = $this->iv;
        $encryptKey = $this->encryptKey;
        //Open module
        @$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
        //print "module = $module <br/>" ;
        @mcrypt_generic_init($module, $encryptKey, $localIV);
        //Padding
        @$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
        $pad = $block - (strlen($encryptStr) % $block); //Compute how many characters need to pad
        $encryptStr .= str_repeat(chr($pad), $pad); // After pad, the str length must be equal to block or its integer multiples
        //encrypt
        @$encrypted = mcrypt_generic($module, $encryptStr);
        //Close
        @mcrypt_generic_deinit($module);
        @mcrypt_module_close($module);
        return base64_encode($encrypted);
    }

    //解密
    public function decrypt($encryptStr) {
        $localIV = $this->iv;
        $encryptKey = $this->encryptKey;
        //Open module
        $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
        //print "module = $module <br/>" ;
        mcrypt_generic_init($module, $encryptKey, $localIV);
        $encryptedData = base64_decode($encryptStr);
        $encryptedData = mdecrypt_generic($module, $encryptedData);

        return $encryptedData;
    }
}
// $encryptString = 'gz1DR+BsCzQe55HFdq1IiQ==';
// $encryptObj = new MagicCrypt();

// $result = $encryptObj->encrypt($encryptString);//加密结果
// $decryptString = $decryptString = $encryptObj->decrypt($result);//解密结果
// echo $result . "<br/>";
// echo $decryptString . "<br/>";
